package com.example.alphabetslider;

import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SectionIndexer;
import android.widget.TextView;

/**
 * A placeholder fragment containing a simple view.
 */
public class MainFrgmt extends Fragment implements SectionIndexer {
	
	float alphaHeight = 1;
	int screenHeight = 0;
	SectionIndexer indexer;
	TextView alphabetTextView;
	ViewTreeObserver.OnPreDrawListener preDrawListener;
	ViewTreeObserver vto;
	ListView list;
	ArrayAdapter<String> adapter;
	String alphabet = "A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\nO\nP\nQ\nR\nS\nT\nU\nV\nW\nX\nY\nZ";
	
	String[] countries = { "Afghanistan", "Albania", "Algeria", "American Samoa",
            "Andorra", "Angola", "Anguilla", "Antarctica",
            "Antigua and Barbuda", "Argentina", "Armenia", "Aruba",
            "Australia", "Austria", "Azerbaijan", "Bahrain", "Bangladesh",
            "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda",
            "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana",
            "Bouvet Island", "Brazil", "British Indian Ocean Territory",
            "British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso",
            "Burundi", "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada",
            "Cape Verde", "Cayman Islands", "Central African Republic", "Chad",
            "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands",
            "Colombia", "Comoros", "Congo", "Cook Islands", "Costa Rica",
            "Croatia", "Cuba", "Cyprus", "Czech Republic",
            "Democratic Republic of the Congo", "Denmark", "Djibouti",
            "Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt",
            "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia",
            "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji",
            "Finland", "Former Yugoslav Republic of Macedonia", "France",
            "French Guiana", "French Polynesia", "French Southern Territories",
            "Gabon", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece",
            "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala",
            "Guinea", "Guinea-Bissau", "Guyana", "Haiti",
            "Heard Island and McDonald Islands", "Honduras", "Hong Kong",
            "Hungary", "Iceland", "India", "Indonesia", "Iran", "Iraq",
            "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan",
            "Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos",
            "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya",
            "Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Madagascar",
            "Malawi", "Malaysia", "Maldives", "Mali", "Malta",
            "Marshall Islands", "Martinique", "Mauritania", "Mauritius",
            "Mayotte", "Mexico", "Micronesia", "Moldova", "Monaco", "Mongolia",
            "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia",
            "Nauru", "Nepal", "Netherlands", "Netherlands Antilles",
            "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria",
            "Niue", "Norfolk Island", "North Korea", "Northern Marianas",
            "Norway", "Oman", "Pakistan", "Palau", "Panama",
            "Papua New Guinea", "Paraguay", "Peru", "Philippines",
            "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar",
            "Reunion", "Romania", "Russia", "Rwanda", "Sqo Tome and Principe",
            "Saint Helena", "Saint Kitts and Nevis", "Saint Lucia",
            "Saint Pierre and Miquelon", "Saint Vincent and the Grenadines",
            "Samoa", "San Marino", "Saudi Arabia", "Senegal", "Seychelles",
            "Sierra Leone", "Singapore", "Slovakia", "Slovenia",
            "Solomon Islands", "Somalia", "South Africa",
            "South Georgia and the South Sandwich Islands", "South Korea",
            "Spain", "Sri Lanka", "Sudan", "Suriname",
            "Svalbard and Jan Mayen", "Swaziland", "Sweden", "Switzerland",
            "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand",
            "The Bahamas", "The Gambia", "Togo", "Tokelau", "Tonga",
            "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan",
            "Turks and Caicos Islands", "Tuvalu", "Uganda",
            "Ukraine", "United Arab Emirates", "United Kingdom",
            "United States", "United States Minor Outlying Islands", "Uruguay",
            "Uzbekistan", "Vanuatu", "Vatican City", "Venezuela", "Vietnam","Virgin Islands",
            "Wallis and Futuna", "Western Sahara", "Yemen", "Yugoslavia",
            "Zambia", "Zimbabwe" };
	
	
	int floatToInt(float f) {
		int i = 0;
		if (f > 0) // 正数
			i = (int) ((f * 10 + 5) / 10);
		else if (f < 0) // 负数
			i = (int) ((f * 10 - 5) / 10);
		else
			i = 0;
		return i;
	}
	
	OnTouchListener touchListener = new View.OnTouchListener() {
		
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				
				float fy = event.getY();
				int start;
				start = (int) (fy / alphaHeight);
				if (start % 2 != 0) {
					if ((fy * 10 + 5 ) / 10 > fy) { //四舍五入 小数部分 > 0.5
						++start;
					}else{
						--start;
					}
				}
				start = start > alphabet.length() ? start - 2 :start;
				System.out.println(String.format("fy = %2f , start = %d , end = %d", fy,start,start + 1));
				SpannableString sp = new SpannableString(alphabet);
				sp.setSpan(new ForegroundColorSpan(Color.parseColor("#FF34B3")),start,start + 1 ,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
				
				alphabetTextView.setText(sp);
				list.setSelection(start);
				break;
			case MotionEvent.ACTION_UP:
				System.out.println("ACTION_UP");
				break;
			case MotionEvent.ACTION_MOVE:
				System.out.println("ACTION_MOVE");
				break;
			default:
				break;
			}
			return false;
		}
	};
	
	/**
	* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	*/ 
	public static int dip2px ( Context context, float dpValue ) { 
		final float scale = context. getResources ( ). getDisplayMetrics ( ). density ; 
		return ( int ) (dpValue * scale + 0.5f ) ; 
	} 

	/**
	* 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	*/ 
	public static int px2dip ( Context context, float pxValue ) { 
		final float scale = context. getResources ( ). getDisplayMetrics ( ). density ; 
		return ( int ) (pxValue / scale + 0.5f ) ; 
	}
	
	public void init() {
		
		ViewTreeObserver vto = alphabetTextView.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            public void onGlobalLayout() {
                //...
                int height,tmp ;
        		Rect rect = new Rect();
        		alphabetTextView.getDrawingRect(rect);//得到当前view的显示区域
        		height = rect.height();//view的显示区域高度,默认以像素为单位，把它转成sp
        		height = alphabetTextView.getHeight();
        		
        		DisplayMetrics dm = new DisplayMetrics();
        		getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        		
				System.out.println(String.format(
						"screen width in pixels: %d ,screen height: %d",dm.widthPixels, dm.heightPixels));
				System.out.println(String.format(
						"densityDpi: %d ,density: %f , scaledDensity : %f:",
						dm.densityDpi, dm.density, dm.scaledDensity));
        		
        		SpannableString sp = new SpannableString(alphabet);  
        		sp.setSpan(new ForegroundColorSpan(Color.parseColor("#FF34B3")),0,1,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        		sp.setSpan(new ForegroundColorSpan(Color.parseColor("#FF34B3")),49,50,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        		alphaHeight = height/26;
        		alphabetTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,alphaHeight);
//        		sp.setSpan(new RelativeSizeSpan(f),0,len - 1,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        		alphabetTextView.setText(sp);
        		
        		alphabetTextView.setOnTouchListener(touchListener);
                
                
                alphabetTextView.getViewTreeObserver().removeGlobalOnLayoutListener(this);//关闭监听
            }
        });
		
		
		
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.frgmt_main, container,false);
		list = (ListView) rootView.findViewById(R.id.list);
		alphabetTextView = (TextView) rootView.findViewById(R.id.alphaset);
		adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,countries);
		list.setAdapter(adapter);
		init();
		return rootView;
	}
	@Override
	public Object[] getSections() {
		return null;
	}

	@Override
	public int getPositionForSection(int sectionIndex) {
		return 0;
	}

	@Override
	public int getSectionForPosition(int position) {
		return 0;
	}
}